import { uploadImg } from '@/api/api'
import Compressor from 'compressorjs'
import { base64AddWaterMaker } from './addWaterMark'
import { getNowFormatDate } from './date'

const addWaterMark = async (file, address) => {
  let resultBase64 = await base64AddWaterMaker(file.content, {
    font: 'microsoft yahei', //字体
    textArray: [address, getNowFormatDate()] //水印文本内容，允许数组最大长度3 即：3行水印
  })
  // 替换图片地址为水印图片
  file.content = resultBase64
  file.url = resultBase64
  console.log(file.content)
  console.log(file)
  let blob = dataURLtoBlob(file.content)
  let waterMarkFile = blobToFile(blob)
  return waterMarkFile
}
//dataURLtoBlob 、 blobToFile 两个方法的意思是把base64的图片转换成file文件
//1,先将base64转换为blob
const dataURLtoBlob = (dataurl) => {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}
//2,再将blob转换为file
const blobToFile = (theBlob) => {
  theBlob.lastModifiedDate = new Date() // 文件最后的修改日期
  theBlob.name = Math.random().toString(36).slice(-8) // 文件名
  return new File([theBlob], Math.random().toString(36).slice(-8), {
    type: theBlob.type,
    lastModified: Date.now()
  })
}
export const compress = async (file, img, searchFormImg) => {
  showLoadingToast({
    message: '图片上传中...',
    forbidClick: true
  })
  if (file.file.size > 1024 * 1024 * 2) {
    new Compressor(file.file, {
      quality: 0.4,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.file.type
        })
        console.log(compressedFile.size)
        if (compressedFile.size > 1024 * 1024 * 2) {
          closeToast()
          img.splice(img.length - 1, 1)
          showFailToast('图片大小超过2M，请重新上传！')
        } else {
          const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
          formData.append('file', compressedFile) //接口需要传的参数
          uploadImg(formData).then((res) => {
            closeToast()
            searchFormImg.push(res)
            showSuccessToast('图片上传成功！')
          })
        }
      },
      error(err) {
        closeToast()
        img.splice(img.length - 1, 1)
        showFailToast('图片上传失败！')
        console.log('compress error: ', err.message)
      }
    })
  } else {
    console.log(file)
    new Compressor(file.file, {
      quality: 0.8,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.file.type
        })
        console.log(compressedFile)
        const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
        formData.append('file', compressedFile) //接口需要传的参数
        uploadImg(formData).then((res) => {
          closeToast()
          searchFormImg.push(res)
          showSuccessToast('图片上传成功！')
        })
      },
      error(err) {
        closeToast()
        img.splice(img.length - 1, 1)
        showFailToast('图片上传失败！')
        console.log('compress error: ', err.message)
      }
    })
  }
}

export const compress2 = async (file, img, finalImg) => {
  showLoadingToast({
    message: '图片上传中...',
    forbidClick: true
  })
  if (file.file.size > 1024 * 1024 * 2) {
    new Compressor(file.file, {
      quality: 0.4,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.file.type
        })
        console.log(compressedFile.size)
        if (compressedFile.size > 1024 * 1024 * 2) {
          closeToast()
          img.splice(img.length - 1, 1)
          showFailToast('图片大小超过2M，请重新上传！')
        } else {
          const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
          formData.append('file', compressedFile) //接口需要传的参数
          uploadImg(formData).then((res) => {
            closeToast()
            finalImg.push(res)
            showSuccessToast('图片上传成功！')
          })
        }
      },
      error(err) {
        closeToast()
        img.splice(img.length - 1, 1)
        showFailToast('图片上传失败！')
        console.log('compress error: ', err.message)
      }
    })
  } else {
    new Compressor(file.file, {
      quality: 0.8,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.file.type
        })
        console.log(compressedFile)
        const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
        formData.append('file', compressedFile) //接口需要传的参数
        uploadImg(formData).then((res) => {
          closeToast()
          finalImg.push(res)
          showSuccessToast('图片上传成功！')
        })
      },
      error(err) {
        closeToast()
        img.splice(img.length - 1, 1)
        showFailToast('图片上传失败！')
        console.log('compress error: ', err.message)
      }
    })
  }
}

// 添加水印
export const compress3 = async (file, searchFormImgs, address) => {
  showLoadingToast({
    message: '图片上传中...',
    forbidClick: true
  })
  if (file.file.size > 1024 * 1024 * 2) {
    const waterMarkFile = await addWaterMark(file, address)
    new Compressor(waterMarkFile, {
      quality: 0.4,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.file.type
        })
        console.log(compressedFile.size)
        if (compressedFile.size > 1024 * 1024 * 2) {
          closeToast()
          searchFormImgs.splice(searchFormImgs.length - 1, 1)
          showFailToast('图片大小超过2M，请重新上传！')
        } else {
          const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
          formData.append('file', compressedFile) //接口需要传的参数
          uploadImg(formData).then((res) => {
            closeToast()
            searchFormImgs[searchFormImgs.length - 1].url = res.url
            showSuccessToast('图片上传成功！')
          })
        }
      },
      error(err) {
        closeToast()
        searchFormImgs.splice(searchFormImgs.length - 1, 1)
        showFailToast('图片上传失败！')
        console.log('compress error: ', err.message)
      }
    })
  } else {
    console.log(file)
    const waterMarkFile = await addWaterMark(file, address)
    new Compressor(waterMarkFile, {
      quality: 0.8,
      success(compressedBlob) {
        let compressedFile = new File([compressedBlob], Math.random().toString(36).slice(-8), {
          type: file.file.type
        })
        console.log(compressedFile)
        const formData = new FormData() //构造一个 FormData，把后台需要发送的参数添加
        formData.append('file', compressedFile) //接口需要传的参数
        uploadImg(formData).then((res) => {
          closeToast()
          console.log(searchFormImgs);
          searchFormImgs[searchFormImgs.length - 1].url = res.url
          showSuccessToast('图片上传成功！')
        })
      },
      error(err) {
        closeToast()
        searchFormImgs.splice(searchFormImgs.length - 1, 1)
        showFailToast('图片上传失败！')
        console.log('compress error: ', err.message)
      }
    })
  }
}
